from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator
import json
from .models import DramaM3u8Link, WechatArticle
from .crawler import run_crawler
from .wechat_crawler import crawl_wechat_article, batch_crawl_articles

@csrf_exempt
def crawl_drama(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            drama_list_url = data.get('drama_list_url')
            episode_list_xpath = data.get('episode_list_xpath')
            drama_name = data.get('drama_name')
            m3u8_filename = data.get('m3u8_filename')
            
            run_crawler(drama_list_url, episode_list_xpath, drama_name, m3u8_filename)
            
            return JsonResponse({'message': '爬虫任务已启动'})
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    
    return JsonResponse({'error': '只支持POST请求'}, status=405)

def drama_m3u8_list(request):
    drama_name = request.GET.get('drama_name', '')
    page = int(request.GET.get('page', 1))
    page_size = int(request.GET.get('page_size', 10))
    
    queryset = DramaM3u8Link.objects.all()
    if drama_name:
        queryset = queryset.filter(drama_name__icontains=drama_name)
    
    queryset = queryset.order_by('-created_time')
    
    paginator = Paginator(queryset, page_size)
    page_obj = paginator.get_page(page)
    
    data = []
    for item in page_obj:
        data.append({
            'id': item.id,
            'drama_name': item.drama_name,
            'episode': item.episode,
            'm3u8_url': item.m3u8_url,
            'mp4_url': item.mp4_url,
            'created_time': item.created_time.strftime('%Y-%m-%d %H:%M:%S')
        })
    
    return JsonResponse({
        'data': data,
        'total': paginator.count,
        'page': page,
        'page_size': page_size,
        'total_pages': paginator.num_pages
    })

@csrf_exempt
def crawl_wechat_article_api(request):
    """爬取单篇公众号文章API"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            article_url = data.get('article_url')
            
            if not article_url:
                return JsonResponse({'error': '请提供文章链接'}, status=400)
            
            result = crawl_wechat_article(article_url)
            return JsonResponse(result)
            
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    
    return JsonResponse({'error': '只支持POST请求'}, status=405)

@csrf_exempt
def batch_crawl_wechat_articles_api(request):
    """批量爬取公众号文章API"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            article_urls = data.get('article_urls', [])
            
            if not article_urls:
                return JsonResponse({'error': '请提供文章链接列表'}, status=400)
            
            results = batch_crawl_articles(article_urls)
            return JsonResponse({
                'success': True,
                'results': results,
                'total': len(results),
                'success_count': len([r for r in results if r.get('success')])
            })
            
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    
    return JsonResponse({'error': '只支持POST请求'}, status=405)

def wechat_article_list(request):
    """获取公众号文章列表API"""
    page = int(request.GET.get('page', 1))
    page_size = int(request.GET.get('page_size', 10))
    search = request.GET.get('search', '')
    
    queryset = WechatArticle.objects.all()
    if search:
        queryset = queryset.filter(title__icontains=search)
    
    queryset = queryset.order_by('-created_time')
    
    paginator = Paginator(queryset, page_size)
    page_obj = paginator.get_page(page)
    
    data = []
    for item in page_obj:
        data.append({
            'id': item.id,
            'title': item.title,
            'content': item.content[:200] + '...' if len(item.content) > 200 else item.content,
            'url': item.url,
            'source': item.source,
            'created_time': item.created_time.strftime('%Y-%m-%d %H:%M:%S')
        })
    
    return JsonResponse({
        'data': data,
        'total': paginator.count,
        'page': page,
        'page_size': page_size,
        'total_pages': paginator.num_pages
    })

def wechat_article_detail(request, article_id):
    """获取公众号文章详情API"""
    try:
        article = WechatArticle.objects.get(id=article_id)
        return JsonResponse({
            'id': article.id,
            'title': article.title,
            'content': article.content,
            'url': article.url,
            'source': article.source,
            'created_time': article.created_time.strftime('%Y-%m-%d %H:%M:%S')
        })
    except WechatArticle.DoesNotExist:
        return JsonResponse({'error': '文章不存在'}, status=404)
